/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.poll.om.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.common.core.util.CollectionUtils;
import com.hopes.bizz.common.core.util.ListBeanUtils;
import com.hopes.bizz.common.core.util.StringUtils;
import com.hopes.bizz.poll.common.constant.MonitorConstant;
import com.hopes.bizz.poll.common.constant.OmConstant;
import com.hopes.bizz.poll.common.constant.PollFactorConstant;
import com.hopes.bizz.poll.factor.entity.PollDisplayFactorEntity;
import com.hopes.bizz.poll.factor.service.PollDisplayFactorService;
import com.hopes.bizz.poll.factor.service.PollFactorInfoService;
import com.hopes.bizz.poll.gis.vo.GisAir;
import com.hopes.bizz.poll.gis.vo.GisWater;
import com.hopes.bizz.poll.information.service.PollTownService;
import com.hopes.bizz.poll.monitor.entity.PollMonitorFactorEntity;
import com.hopes.bizz.poll.monitor.entity.PollMonitorSiteEntity;
import com.hopes.bizz.poll.monitor.service.PollMonitorFactorService;
import com.hopes.bizz.poll.monitor.service.PollMonitorSiteService;
import com.hopes.bizz.poll.monitor.service.PollMonitorTypeService;
import com.hopes.bizz.poll.om.bo.OmData;
import com.hopes.bizz.poll.om.dto.PollRtDataDTO;
import com.hopes.bizz.poll.om.entity.BaseOmDataEntity;
import com.hopes.bizz.poll.om.entity.PollRtDataEntity;
import com.hopes.bizz.poll.om.entity.PollRtDataHisEntity;
import com.hopes.bizz.poll.om.mapper.PollRtDataMapper;
import com.hopes.bizz.poll.om.service.*;
import com.hopes.bizz.poll.om.vo.*;
import com.hopes.bizz.poll.pollaqi.entity.Aqi;
import com.hopes.bizz.poll.town.service.PollTownRtDataService;
import com.hopes.boss.common.security.util.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 实时监控数据
 *
 * @author ljh
 * @date 2023-05-22 17:05:57
 */
@Service
public class PollRtDataServiceImpl extends ServiceImpl<PollRtDataMapper, PollRtDataEntity> implements PollRtDataService {
    @Autowired
    private PollRtDataHisService pollRtDataHisService;
    @Autowired
    private PollMonitorSiteService pollMonitorSiteService;
    @Autowired
    private PollDisplayFactorService pollDisplayFactorService;
    @Autowired
    private PollFactorInfoService pollFactorInfoService;
    @Autowired
    private PollMonitorFactorService pollMonitorFactorService;
    @Autowired
    @Lazy
    private PollMinService pollMinService;
    @Autowired
    @Lazy
    private PollHourService pollHourService;
    @Autowired
    @Lazy
    private PollDayService pollDayService;
    @Autowired
    private PollMonitorTypeService pollMonitorTypeService;
    @Autowired
    private PollTownService pollTownService;
    @Autowired
    private PollTownRtDataService pollTownRtDataService;

    @Override
    public void saveHJ212Data(BaseOmDataEntity omDataEntity, String data) {
        // 保存实时数据
        PollRtDataEntity pollRtDataEntity = new PollRtDataEntity();
        BeanUtils.copyProperties(omDataEntity, pollRtDataEntity);
        pollRtDataEntity.setDataType(OmConstant.DATA_TYPE_RT);
        this.deleteByMonitorSiteIdAndDataType(pollRtDataEntity);
        this.save(pollRtDataEntity);

        // 保存历史数据
        PollRtDataHisEntity pollRtDataHisEntity = new PollRtDataHisEntity();
        BeanUtils.copyProperties(omDataEntity, pollRtDataHisEntity);
        pollRtDataHisService.deleteByMonitorSiteIdAndDataTime(pollRtDataHisEntity);
        pollRtDataHisService.save(pollRtDataHisEntity);
    }


    @Override
    public void uploadData(List<PollRtDataDTO> pollUploadDataList) {
        List<PollRtDataDTO> uniquePollUploadDataList = pollUploadDataList.stream()
                .distinct()
                .collect(Collectors.toList());
        List<BaseOmDataEntity> dataList = ListBeanUtils.copyListProperties(uniquePollUploadDataList, BaseOmDataEntity::new);
        dataList.forEach(omDataEntity -> {
            // 计算WQI 水质 共用aqi字段
            Double wqi = computerWQI(omDataEntity.getMonitorSiteId(), omDataEntity.getDataJson());
            omDataEntity.setAqiData(wqi);
            omDataEntity.setOrgId(SecurityUtils.getOrgId());
            // 处理实时数据
            PollRtDataEntity pollRtDataEntity = new PollRtDataEntity();
            BeanUtils.copyProperties(omDataEntity, pollRtDataEntity);
            pollRtDataEntity.setDataType(OmConstant.DATA_TYPE_RT);
            this.deleteByMonitorSiteIdAndDataType(pollRtDataEntity);
            this.save(pollRtDataEntity);
            // 处理历史数据
            PollRtDataHisEntity pollRtDataHisEntity = new PollRtDataHisEntity();
            BeanUtils.copyProperties(omDataEntity, pollRtDataHisEntity);
            pollRtDataHisService.deleteByMonitorSiteIdAndDataTime(pollRtDataHisEntity);
            pollRtDataHisService.save(pollRtDataHisEntity);
        });
    }

    private Double computerWQI(Long id, JSONObject data) {
        try {
            // 计算WQI的值 水质 共用aqi字段
            Aqi wqi = pollRtDataHisService.calculateWQI(data);
            if (ObjectUtil.isNotEmpty(wqi)) {
                return wqi.getAqi();
            }
            return null;
        } catch (Exception e) {
            log.error("实时WQI计算出错");
            return null;
        }
    }

    public void deleteByMonitorSiteIdAndDataType(BaseOmDataEntity omDataEntity) {
        this.baseMapper.deleteByMonitorSiteIdAndDataType(omDataEntity);
    }

    @Override
    public PollAnalysisDataVO trendAnalysis(PollRtDataDTO pollRtDataDTO) {
        // 时间集合
        ArrayList<String> timeList = new ArrayList<>();
        // 因子的报警限值
        JSONObject limitAlarm = selectLimitAlarm(pollRtDataDTO);
        // 数据类型 实时，分钟，小时，天
        Integer dataType = pollRtDataDTO.getDataType();
        if (dataType.equals(OmConstant.DATA_TYPE_RT)) {
            // 实时
            return getPollAnalysisDataVO(pollRtDataHisService, pollRtDataDTO, timeList, limitAlarm);

        } else if (dataType.equals(OmConstant.DATA_TYPE_MIN)) {
            // 分钟
            return getPollAnalysisDataVO(pollMinService, pollRtDataDTO, timeList, limitAlarm);

        } else if (dataType.equals(OmConstant.DATA_TYPE_HOUR)) {
            // 小时
            return getPollAnalysisDataVO(pollHourService, pollRtDataDTO, timeList, limitAlarm);

        } else if (dataType.equals(OmConstant.DATA_TYPE_DAY)) {
            // 天
            return getPollAnalysisDataVO(pollDayService, pollRtDataDTO, timeList, limitAlarm);

        }

        return null;
    }

    // 构建最终数据
    private PollAnalysisDataVO getPollAnalysisDataVO(PollAnalysisService pollAnalysisService, PollRtDataDTO pollRtDataDTO, ArrayList<String> timeList, JSONObject limitAlarm) {
        List<PollRtDataVO> hisData = pollAnalysisService.queryByTimeAndMonitor(pollRtDataDTO)
                .stream()
                .filter(item -> timeList.add(item.getDataTimeStr()))
                .collect(Collectors.toList());
        List<Double> data;
        String dataSign;
        // 判断是不是折算值
        if (pollRtDataDTO.getZs()) {
            // 如果是折算值
            data = buildZsData(hisData, limitAlarm.getString("factorCode"));
            dataSign = "折算";
        } else {
            // 不是折算值
            data = buildData(hisData, limitAlarm.getString("factorCode"));
            dataSign = "实时";
        }
        PollAnalysisDataVO pollAnalysisDataVO = new PollAnalysisDataVO();
        pollAnalysisDataVO.setDataList(data);
        pollAnalysisDataVO.setTimeList(timeList);
        pollAnalysisDataVO.setLimitAlarm(limitAlarm);
        pollAnalysisDataVO.setName(limitAlarm.getString("name") + dataSign + "数据趋势");

        return pollAnalysisDataVO;
    }

    // 根据监控点和因子id查询因子的限值
    private JSONObject selectLimitAlarm(PollRtDataDTO pollRtDataDTO) {
        LambdaQueryWrapper<PollMonitorFactorEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PollMonitorFactorEntity::getFactorId, pollRtDataDTO.getFactorId())
                .eq(PollMonitorFactorEntity::getMonitorSiteId, pollRtDataDTO.getMonitorSiteId());
        PollMonitorFactorEntity entity = pollMonitorFactorService.getOne(wrapper);
        JSONObject res = new JSONObject();
        res.put("maxAlarm", entity.getMaxAlarm() == null ? 0 : entity.getMaxAlarm());
        res.put("minAlarm", entity.getMinAlarm() == null ? 0 : entity.getMinAlarm());
        res.put("factorCode", entity.getFactorCode());
        res.put("statisticUnit", entity.getStatisticUnit() == null ? 0 : entity.getStatisticUnit());
        res.put("name", entity.getFactorIdStr());
        return res;
    }


    // 构建折算值
    private List<Double> buildZsData(List<PollRtDataVO> hisData, String factorCode) {
        ArrayList<Double> list = new ArrayList<>();
        for (PollRtDataVO hisDatum : hisData) {
            JSONObject map = hisDatum.getDataJson();
            JSONObject code = map.getJSONObject(factorCode);
            if (ObjectUtil.isNotEmpty(code)){
                OmData data = JSONObject.toJavaObject(code, OmData.class);
                BigDecimal zsval = data.getZsval();// 折算值
                list.add(zsval.doubleValue());
            }
        }
        return list;
    }

    // 构建实时数据非折算值
    private List<Double> buildData(List<PollRtDataVO> hisData, String factorCode) {
        ArrayList<Double> list = new ArrayList<>();
        for (PollRtDataVO hisDatum : hisData) {
            JSONObject map = hisDatum.getDataJson();
            JSONObject code = map.getJSONObject(factorCode);
            if (ObjectUtil.isNotEmpty(code)){
                OmData data = JSONObject.toJavaObject(code, OmData.class);
                BigDecimal val = data.getVal();
                list.add(val.doubleValue());
            }
        }
        return list;
    }

    @Override
    public Page<PollRtDataVO> queryByMonitorAndTimeType(Page<PollRtDataVO> page, PollRtDataDTO pollRtDataDTO) {
        // 查询站点
        LambdaQueryWrapper<PollMonitorSiteEntity> monitorWrapper = new LambdaQueryWrapper<>();
        // 站点类型
        monitorWrapper.eq(ObjectUtil.isNotEmpty(pollRtDataDTO.getMonitorType()), PollMonitorSiteEntity::getMonitorType, pollRtDataDTO.getMonitorType());
        // 企业
        monitorWrapper.eq(ObjectUtil.isNotEmpty(pollRtDataDTO.getOrgId()), PollMonitorSiteEntity::getOrgId, pollRtDataDTO.getOrgId());
        // 站点id
        monitorWrapper.eq(ObjectUtil.isNotEmpty(pollRtDataDTO.getMonitorSiteId()), PollMonitorSiteEntity::getId, pollRtDataDTO.getMonitorSiteId());
        // 所属乡镇
        monitorWrapper.eq(ObjectUtil.isNotEmpty(pollRtDataDTO.getTownId()), PollMonitorSiteEntity::getTownId, pollRtDataDTO.getTownId());
        // 站点大类
        if (Objects.nonNull(pollRtDataDTO.getMonitorTypeMain())) {
            List<Integer> monitorTypeByMain = pollMonitorTypeService.getMonitorTypeByMain(pollRtDataDTO.getMonitorTypeMain());
            monitorWrapper.in(PollMonitorSiteEntity::getMonitorType, monitorTypeByMain);
        }

        List<Long> idList = pollMonitorSiteService.list(monitorWrapper).stream().map(PollMonitorSiteEntity::getId).collect(Collectors.toList());
        // 根据站点类型和时间类型查询数据
        pollRtDataDTO.setIdList(idList);
        if (CollectionUtils.isEmpty(idList)) {
            return new Page<>();
        }
        Page<PollRtDataVO> pollRtDataPage = baseMapper.selectPageByMonitorSiteIdAndDataType(page, pollRtDataDTO);
        // 只显示要展示的数据
        for (PollRtDataVO pollRtDataVO : pollRtDataPage.getRecords()) {
            JSONObject jsonObject = buildDisplayData(pollRtDataDTO.getMonitorTypeMain(), pollRtDataDTO.getMonitorType(), pollRtDataVO.getDataJson(), pollRtDataVO.getMonitorSiteId());
            pollRtDataVO.setDataJson(jsonObject);
        }
        return pollRtDataPage;
    }

    // 构建要展示的数据
    private JSONObject buildDisplayData(Integer monitorTypeMain, Integer monitorType, JSONObject data, Long monitorSiteId) {
        if (data == null) {
            return new JSONObject();
        }
        LambdaQueryWrapper<PollDisplayFactorEntity> wrapper = new LambdaQueryWrapper<>();
        String ids = null;
        if (ObjectUtil.isNotNull(monitorTypeMain)) {
            List<Integer> monitorTypeList = pollMonitorTypeService.getMonitorTypeByMain(monitorTypeMain);
            wrapper.in(PollDisplayFactorEntity::getMonitorType, monitorTypeList);
            ids = pollDisplayFactorService.list(wrapper).stream().map(PollDisplayFactorEntity::getFactorIds).collect(Collectors.joining());
        } else if (ObjectUtil.isNotNull(monitorType)) {
            wrapper.eq(PollDisplayFactorEntity::getMonitorType, monitorType);
            ids = pollDisplayFactorService.getOne(wrapper).getFactorIds();
        }
        if (StringUtils.isEmpty(ids)) {
            // 展示因子为空
            return new JSONObject();
        }
        // 获取展示因子id
        LambdaQueryWrapper<PollMonitorFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
        List<String> factorIds = CollectionUtils.arrayToList(ids.split(","));
        queryWrapper.in(CollectionUtils.isNotEmpty(factorIds), PollMonitorFactorEntity::getFactorId, factorIds);
        queryWrapper.eq(ObjectUtil.isNotEmpty(monitorSiteId), PollMonitorFactorEntity::getMonitorSiteId, monitorSiteId);
        // 查询展示因子详细信息
        List<PollMonitorFactorEntity> pollFactorInfoList = pollMonitorFactorService.list(queryWrapper);
        JSONObject res = new JSONObject();
        for (PollMonitorFactorEntity pollMonitorFactor : pollFactorInfoList) {
            String code = pollMonitorFactor.getFactorCode();
            JSONObject jsonObject = data.getJSONObject(code);
            if (ObjectUtil.isNotNull(jsonObject)) {
                jsonObject.put("minRange", pollMonitorFactor.getMinRange());
                jsonObject.put("maxRange", pollMonitorFactor.getMaxRange());
                res.put(pollMonitorFactor.getFactorCode(), jsonObject);
            }
        }

        return res;
    }

    @Override
    public AQISort getAqiSort() {
        ArrayList<String> name = new ArrayList<>();
        ArrayList<Double> PM2_5List = new ArrayList<>();
        ArrayList<Double> PM10List = new ArrayList<>();
        ArrayList<Double> COList = new ArrayList<>();
        ArrayList<Double> NO2List = new ArrayList<>();
        ArrayList<Double> O3List = new ArrayList<>();
        ArrayList<Double> SO2List = new ArrayList<>();
        ArrayList<Double> AQIList = new ArrayList<>();
        List<Long> monitorSiteList = pollMonitorSiteService.lambdaQuery()
                .eq(PollMonitorSiteEntity::getAqiFlag, MonitorConstant.IS_AQI_MONITOR)
                .list().stream().map(PollMonitorSiteEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(monitorSiteList)) {
            return null;
        }
        // 获取监控点实时数据
        List<PollRtDataEntity> pollRtDataEntities = baseMapper.selectList(Wrappers.lambdaQuery(PollRtDataEntity.class).in(PollRtDataEntity::getMonitorSiteId, monitorSiteList)
                        .eq(PollRtDataEntity::getDataType, OmConstant.DATA_TYPE_RT)).stream()
                .filter(item -> ObjectUtil.isNotNull(item.getAqiData()))
                .sorted(Comparator.comparing(PollRtDataEntity::getAqiData).reversed()).collect(Collectors.toList());
        // 计算平均值
        double PM2_5, PM10, CO, NO2, O3, SO2, AQI;
        for (PollRtDataEntity pollRtDataEntity : pollRtDataEntities) {
            name.add(pollRtDataEntity.getMonitorSiteStr());
            JSONObject dataJson = pollRtDataEntity.getDataJson();
            if (dataJson.containsKey(PollFactorConstant.PM2_5)) {
                PM2_5 = dataJson.getJSONObject(PollFactorConstant.PM2_5).getDouble(OmConstant.VAL);
                PM2_5List.add(PM2_5);
            }
            if (dataJson.containsKey(PollFactorConstant.PM10)) {
                PM10 = dataJson.getJSONObject(PollFactorConstant.PM10).getDouble(OmConstant.VAL);
                PM10List.add(PM10);
            }
            if (dataJson.containsKey(PollFactorConstant.CO)) {
                CO = dataJson.getJSONObject(PollFactorConstant.CO).getDouble(OmConstant.VAL);
                COList.add(CO);
            }
            if (dataJson.containsKey(PollFactorConstant.NO2)) {
                NO2 = dataJson.getJSONObject(PollFactorConstant.NO2).getDouble(OmConstant.VAL);
                NO2List.add(NO2);
            }
            if (dataJson.containsKey(PollFactorConstant.O3)) {
                O3 = dataJson.getJSONObject(PollFactorConstant.O3).getDouble(OmConstant.VAL);
                O3List.add(O3);
            }
            if (dataJson.containsKey(PollFactorConstant.SO2)) {
                SO2 = dataJson.getJSONObject(PollFactorConstant.SO2).getDouble(OmConstant.VAL);
                SO2List.add(SO2);
            }
            AQI = pollRtDataEntity.getAqiData();
            AQIList.add(AQI);
        }
        AQIData aqiData = new AQIData();
        aqiData.setPM2_5(PM2_5List);
        aqiData.setPM10(PM10List);
        aqiData.setCO(COList);
        aqiData.setNO2(NO2List);
        aqiData.setO3(O3List);
        aqiData.setSO2(SO2List);
        aqiData.setAQI(AQIList);
        AQISort aqiSort = new AQISort();
        aqiSort.setTownName(name);
        aqiSort.setData(aqiData);
        return aqiSort;
    }

    @Override
    public WQISort getWqiSort(Integer monitorType) {
            ArrayList<String> name = new ArrayList<>();
            ArrayList<Double> PHList = new ArrayList<>();
            ArrayList<Double> CODList = new ArrayList<>();
            ArrayList<Double> NHList = new ArrayList<>();
            ArrayList<Double> TPList = new ArrayList<>();
            ArrayList<Double> BOD5List = new ArrayList<>();
            ArrayList<Double> DOList = new ArrayList<>();
            ArrayList<Double> WQIList = new ArrayList<>();
//            List<Integer> monitorTypeByMain = pollMonitorTypeService.getMonitorTypeByMain(MonitorConstant.MONITOR_TYPE_WATER);

            List<Long> monitorSiteList = pollMonitorSiteService.lambdaQuery().eq(PollMonitorSiteEntity::getMonitorType,monitorType)
                    .list().stream().map(PollMonitorSiteEntity::getId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(monitorSiteList)) {
                return null;
            }
            // 获取监控点实时数据
            List<PollRtDataEntity> pollRtDataEntities = baseMapper.selectList(Wrappers.lambdaQuery(PollRtDataEntity.class).in(PollRtDataEntity::getMonitorSiteId, monitorSiteList)
                            .eq(PollRtDataEntity::getDataType, OmConstant.DATA_TYPE_RT)).stream()
                    .filter(item -> ObjectUtil.isNotNull(item.getAqiData()))
                    .sorted(Comparator.comparing(PollRtDataEntity::getAqiData).reversed()).collect(Collectors.toList());
            // 计算平均值
            Double PH, COD, NH, TP, BOD5, DO, WQI;
            for (PollRtDataEntity pollRtDataEntity : pollRtDataEntities) {
                name.add(pollRtDataEntity.getMonitorSiteStr());
                JSONObject dataJson = pollRtDataEntity.getDataJson();
                if (dataJson.containsKey(PollFactorConstant.PH)) {
                    PH = dataJson.getJSONObject(PollFactorConstant.PH).getDouble(OmConstant.VAL);
                    PHList.add(PH);
                } else {
                    PHList.add(0.0);
                }

                if (dataJson.containsKey(PollFactorConstant.COD)) {
                    COD = dataJson.getJSONObject(PollFactorConstant.COD).getDouble(OmConstant.VAL);
                    CODList.add(COD);
                }else{
                    CODList.add(0.0);
                }

                if (dataJson.containsKey(PollFactorConstant.NH)) {
                    NH = dataJson.getJSONObject(PollFactorConstant.NH).getDouble(OmConstant.VAL);
                    NHList.add(NH);
                }else {
                    NHList.add(0.0);
                }

                if (dataJson.containsKey(PollFactorConstant.TP)) {
                    TP = dataJson.getJSONObject(PollFactorConstant.TP).getDouble(OmConstant.VAL);
                    TPList.add(TP);
                }else {
                    TPList.add(0.0);
                }

                if (dataJson.containsKey(PollFactorConstant.BOD5)) {
                    BOD5 = dataJson.getJSONObject(PollFactorConstant.BOD5).getDouble(OmConstant.VAL);
                    BOD5List.add(BOD5);
                }else {
                    BOD5List.add(0.0);
                }

                if (dataJson.containsKey(PollFactorConstant.DO)) {
                    DO = dataJson.getJSONObject(PollFactorConstant.DO).getDouble(OmConstant.VAL);
                    DOList.add(DO);
                }else {
                    DOList.add(0.0);
                }

                WQI = pollRtDataEntity.getAqiData();
                WQIList.add(WQI);
            }
            WQIData wqiData = new WQIData();
            wqiData.setPH(PHList);
            wqiData.setCOD(CODList);
            wqiData.setNH(NHList);
            wqiData.setTP(TPList);
            wqiData.setBOD5(BOD5List);
            wqiData.setDO(DOList);
            wqiData.setWQI(WQIList);
            WQISort wqiSort = new WQISort();
            wqiSort.setName(name);
            wqiSort.setData(wqiData);
            return wqiSort;
    }
    @Override
    public List<GisAir> queryGisAirMonitor() {
        // 站点类型
        List<Integer> monitorType = pollMonitorTypeService.getMonitorTypeByMain(MonitorConstant.MONITOR_TYPE_AIR);
        if (CollectionUtils.isEmpty(monitorType)) {
            return null;
        }
        List<GisAir> gisAirList = pollMonitorSiteService.queryGisAirMonitor(monitorType, MonitorConstant.IS_AQI_MONITOR, OmConstant.DATA_TYPE_RT);
        for (GisAir gisAir : gisAirList) {
            JSONObject jsonObject = buildGisDisplayData(MonitorConstant.MONITOR_TYPE_AIR, gisAir.getDataJson(), gisAir.getId());
            gisAir.setDataJson(jsonObject);
        }
        return gisAirList;
    }

    @Override
    public List<GisWater> queryGisWaterMonitor() {
        // 站点类型
        List<Integer> monitorType = pollMonitorTypeService.getMonitorTypeByMain(MonitorConstant.MONITOR_TYPE_WATER);
        if (CollectionUtils.isEmpty(monitorType)) {
            return null;
        }
        List<GisWater> gisWaterList = pollMonitorSiteService.queryGisWaterMonitor(monitorType, OmConstant.DATA_TYPE_RT);
        for (GisWater gisWater : gisWaterList) {
            JSONObject jsonObject = buildGisDisplayData(MonitorConstant.MONITOR_TYPE_WATER, gisWater.getDataJson(), gisWater.getId());
            gisWater.setDataJson(jsonObject);
        }
        return gisWaterList;
    }

    // 构建要展示的数据
    private JSONObject buildGisDisplayData(Integer monitorTypeMain, JSONObject data, Long monitorSiteId) {
        LambdaQueryWrapper<PollDisplayFactorEntity> wrapper = new LambdaQueryWrapper<>();
        List<Integer> monitorTypeList = pollMonitorTypeService.getMonitorTypeByMain(monitorTypeMain);
        wrapper.in(PollDisplayFactorEntity::getMonitorType, monitorTypeList);
        String ids = pollDisplayFactorService.list(wrapper).stream().map(PollDisplayFactorEntity::getFactorIds).collect(Collectors.joining());

        // 获取展示因子id
        LambdaQueryWrapper<PollMonitorFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
        List<String> factorIds;
        if (StringUtils.isEmpty(ids)) {
            // 展示因子为空
            return new JSONObject();
        }
        factorIds = CollectionUtils.arrayToList(ids.split(","));
        queryWrapper.in(CollectionUtils.isNotEmpty(factorIds), PollMonitorFactorEntity::getFactorId, factorIds);
        queryWrapper.eq(ObjectUtil.isNotEmpty(monitorSiteId), PollMonitorFactorEntity::getMonitorSiteId, monitorSiteId);
        // 查询展示因子详细信息
        List<PollMonitorFactorEntity> pollFactorInfoList = pollMonitorFactorService.list(queryWrapper);
        JSONObject res = new JSONObject();
        for (PollMonitorFactorEntity pollMonitorFactor : pollFactorInfoList) {
            String code = pollMonitorFactor.getFactorCode();
            JSONObject jsonObject = data.getJSONObject(code);
            if (ObjectUtil.isNotNull(jsonObject)) {
                res.put(pollMonitorFactor.getFactorIdStr(), jsonObject);
            }
        }

        return res;
    }

    @Override
    public List<GisAir> gisAirMonitorRt() {
        List<GisAir> gisAirs = baseMapper.gisAirMonitorRt();
        for (GisAir gisAir : gisAirs) {
            gisAir.setDataJson(buildGisDisplayData(MonitorConstant.MONITOR_TYPE_AIR, gisAir.getDataJson(), gisAir.getId()));
        }
        return gisAirs;
    }
}
